package org.codeart.map.remote;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.codeart.common.constant.MapResultKey;
import org.codeart.common.response.DirectionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static java.util.stream.Collectors.joining;

@Slf4j
@Service
public class MapDirectionClient {

    // https://restapi.amap.com/v3/direction/driving
    @Value("${system.map.path-api}")
    private String mapUrl;

    @Value("${system.map.key}")
    private String userKey;

    @Autowired
    private RestTemplate restTemplate;

    public DirectionResponse direction(String depLongitude, String depLatitude, String destLongitude,
                                       String destLatitude) {
        Map<String, String> conditions = new HashMap<String, String>() {{
            put("origin", depLongitude + "," + depLatitude);
            put("destination", destLongitude + "," + destLatitude);
            put("key", userKey);
        }};

        String s = conditions.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(joining("&"));
        String url = mapUrl + "?" + s;
        log.info("调用的接口地址: {}", url);

        // 调用高德接口
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        log.info("高德地图路径规划返回信息: {}", response.getBody());

        // 解析接口
        return parseDirectionEntity(response.getBody());
    }

    private DirectionResponse parseDirectionEntity(String pathJson) {
        DirectionResponse directionResponse = new DirectionResponse();
        try {
            JSONObject jsonObject = JSONObject.parseObject(pathJson);
            Optional.ofNullable(jsonObject)
                    .map(obj -> jsonObject.getInteger(MapResultKey.STATUS))
                    .filter(obj -> obj == 1)
                    .map(obj -> jsonObject.getJSONObject(MapResultKey.ROUTE))
                    .map(obj -> obj.getJSONArray(MapResultKey.PATHS))
                    .map(obj -> obj.getJSONObject(0))
                    .ifPresent(obj -> {
                        if (obj.containsKey(MapResultKey.DISTANCE)) {
                            directionResponse.setDistance(obj.getInteger(MapResultKey.DISTANCE));
                        }
                        if (obj.containsKey(MapResultKey.DURATION)) {
                            directionResponse.setDuration(obj.getInteger(MapResultKey.DURATION));
                        }
                    });
        } catch (Exception e) {
            return null;
        }
        return directionResponse;
    }

}
